import React from 'react';
import * as PropTypes from 'prop-types';

import { Select } from 'antd';
const { Option } = Select;

class CustomSelect extends React.Component {
  static defaultProps = {
    columns: [],
    size: 'small',
  }

  constructor(props) {
    super(props);

    let value;
    if ('defaultValue' in props) {
      value = props.defaultValue;
    }
    this.state = {
      value,
    };
  }

  /**
   * 监测指标
   */
  handleChange = (value) => {
    const lastValue = this.state.value;

    const { onChange } = this.props;
    if (onChange && value !== lastValue) {
      this.setState({
        value
      })
      onChange(value)
    }
  }

  render() {
    const { columns, size, styleObj = { width: '100px' } } = this.props;
    const { value } = this.state;
    return (
      <Select
        size={size}
        style={styleObj}
        defaultValue={value}
        onChange={this.handleChange}
      >
        {
          columns.map(item =>{
            const { label, value } = item;
            return (
              <Option key={value} value={value}>{label}</Option>
            )
          }
        )}
      </Select>);
  }
}

CustomSelect.propTypes = {
  columns: PropTypes.array,
  onChange: PropTypes.func,
}
export default CustomSelect;
